#!/usr/bin/python

import os
from nMedia import nMedia
nMedia = nMedia(debug=False)
Content = nMedia.Content
import re

DIRECTORY_TAGS = (
	#Format regex match, tag attached
	(re.compile("AC3"),["AC3"]),
	(re.compile("DVDRIP",re.IGNORECASE),["DVDRiP"]),
	(re.compile("DVDSCR|DVD\.SCREENER|\.SCREENER",re.IGNORECASE),["DVDSCR"]),
	(re.compile("HDTV",re.IGNORECASE),["HDTV"]),
	(re.compile("XviD",re.IGNORECASE),["XviD"]),
	(re.compile("DivX",re.IGNORECASE),["DivX"]),
	(re.compile("SVCD",re.IGNORECASE),["SVCD"]),
	(re.compile("\.WS\."),["Widescreen"]),
	(re.compile("\.5\.\.1\."),["Surround","AC3"]),
	(re.compile("\.6\.\.1\."),["Surround","AC3"]),
	(re.compile("\.7\.\.1\."),["Surround","AC3"]),
	(re.compile("\.FS\."),["Fullscreen"]),
	(re.compile("\.R5\."),["R5"]),
	(re.compile("\.HD\."),["HD"]),
	(re.compile("EXTENDED(\.EDITION)?"),["Extended"]),
	(re.compile("UNRATED",re.IGNORECASE),["UNRATED"]),
)

#Things to strip from the path
DIRECTORY_IGNORE = re.compile("-[a-z0-9]$|SUBBED|RETAIL|FINAL|PROPER|REPACK|LIMITED|UNSUBBED|INTERNAL|RERIP|\-[A-Za-z0-9]*$",re.IGNORECASE)
DIRECTORY_CAPS = re.compile("[A-Z]{4,10}")

DIRECTORY_YEAR = re.compile("[0-9]{4}",re.IGNORECASE)

class ImportDirectory:
	def ScanDirectory(self,fullPath,path,extraTags):
		stripLength = len(fullPath) + len(path) + 1
		fullTarget = os.path.join(fullPath,path)
		imdbId = None
		
		if not Content.GetDirectory(fullTarget):
			#Find all text files and scan them for imdb links.
			for (dirpath, dirnames, filenames) in os.walk(fullTarget):
				for filename in filenames:
					filename = os.path.join(dirpath,filename)
					if os.stat(filename).st_size < (20 * 1024): #small files should be scanned for links
						#TODO : Scan for imdb.com/themoviedb.org links
						match = nMedia.IMDB_URL.findall(open(filename,"r").read())
						if match:
							imdbId = match[0]
			
			#We need to add this content:
			title,year,tags = self.ParseDirectory(path)
			#First add the content:
			contentId = Content.AddContent({'title':title,'released':year})
			#Add the tags:
			for tag in tags:
				tagId = Content.GetTag(tag,"Files")
				Content.LinkTag(contentId,tagId)
				
			for tag in extraTags:
				tagId = Content.GetTag(tag,None)
				Content.LinkTag(contentId,tagId)
				
			#Then the directory to the content:
			pathId = Content.AddDirectory(contentId,fullTarget)
			#Then all the files:
			Content.ScanDirectory(pathId)
			if imdbId:
				Content.AddUrl(contentId,"http://www.imdb.com/title/%s/" % (imdbId))
				#print "Adding url",contentId,imdbId
				nMedia.CheckUrls(contentId)
			#print title,imdbId
			
		Content.conn.commit()
		
	def __init__(self,fullPath,tags):
		print "importing",fullPath
		for dir in os.listdir(fullPath):
			self.ScanDirectory(fullPath,dir,tags)
			
	def ParseDirectory(self,path):
		#Get the tags 
		tags = []
		for (regex,extratags) in DIRECTORY_TAGS:
			if regex.search(path):
				for tag in extratags:
					tags.append(tag)
					
		for (regex,extratags) in DIRECTORY_TAGS:
			path = regex.sub("",path)

		path = DIRECTORY_IGNORE.sub("",path)
		
		#Get the year and remove it from the path
		year = DIRECTORY_YEAR.findall(path)
		if len(year) == 1:
			year = year[0]
		else:
			year = None
		path = DIRECTORY_YEAR.sub("",path)
		
		#Lets strip all stuff in CAPSLOCK ASLONG as the resulting length of the path isn't halfed.
		x = DIRECTORY_CAPS.findall(path)
		if x:
			p = DIRECTORY_CAPS.sub("",path)
			if len(p) > len(path) / 2:
				path = p
		
		return (path.replace("."," ").strip(),year,tags,)
		
		
ImportDirectory("/mnt/storage/dump/Movies",["Movie"])
ImportDirectory("/mnt/storage/dump/Series",["Series"])
